'use strict'

const Controller = require('egg').Controller

class QuestionController extends Controller {

    async getNoReplyQuestion () {
        const { ctx } = this
        const { user_id } = ctx.query
        const docs = await ctx.model.Question.find({ reply_user_id:{ $nin:[user_id] },user_id:{ $nin:[user_id] } },{
            content:0,
            content_html:0
        }).populate({
            path:'user_id',
            select:{ avatar:1,nickname:1 }
        }).sort({ _id:-1 }).limit(16)


        ctx.body = {
            state:'ok',
            data:docs
        }
    }

    async Create () {
        const { ctx } = this
        const { title,content,content_html,topic,image_field } = ctx.request.body
        const docs = await ctx.model.Question.create({
            title,
            content,
            content_html,
            topic,
            user_id:ctx.user._id,
            image_field
        })
        ctx.body = {
            state:'ok',
            data:docs
        }
        await Promise.all([
            ctx.model.User.updateOne({ _id:ctx.user._id },{ $inc:{ question_count:1 } }),
            ctx.model.Dynamic.create({ user_id:ctx.user._id,type:'提出了问题',question_id:docs._id })
        ])
    }

    async RecommendListData () {
        const { ctx } = this
        const { page } = ctx.query

        const docs = await ctx.model.Reply.find()
            .select({ content_html:0,comment:0 })
            .populate({
                path:'user_id',
                select:{ avatar:1,nickname:1,one_sentence_introduction:1 }
            })
            .populate({ path:'question_id',select:{ title:1,reply_count:1 } })
            .sort({ _id:-1 })
            .skip((page - 1) * 8)
            .limit(8)
        ctx.body = {
            state:'ok',
            data:docs
        }

    }

    async RecommendList () {
        const { ctx } = this
        const { page,type } = ctx.query
        const topic = {
            'shenghuo':'生活',
            'jiaoyu':'教育',
            'yule':'娱乐',
            'qiche':'汽车',
            'jinrong':'金融',
            'zhichang':'职场',
            'keji':'科技',
            'tiyu':'体育'
        }
        let docs
        if (!type) {
            docs = await ctx.model.Question
                .find()
                .populate({
                    path:'reply_id.reply',
                    select:{ content:1,like_count:1,comment_count:1,image_field:1 }
                })
                .populate({
                    path:'reply_id.user',
                    select:{ nickname:1 }
                })
                .sort({ _id:-1 })
                .skip((page - 1) * 8)
                .limit(8)
        }
        if (type) {
            docs = await ctx.model.Question
                .find({ topic:{ $in:[topic[type]] } })
                .populate({
                    path:'reply_id.reply',
                    select:{ content:1,like_count:1,comment_count:1,image_field:1 }
                })
                .populate({
                    path:'reply_id.user',
                    select:{ nickname:1 }
                })
                .sort({ _id:-1 })
                .skip((page - 1) * 8)
                .limit(8)
        }


        ctx.body = {
            state:'ok',
            data:docs,
        }
    }

    async findOne () {
        const { ctx } = this
        try {
            const { _id } = ctx.query
            const docs = await ctx.model.Question.findOne({ _id })
            if (!docs) return ctx.body = { state:'err',errMsg:'不存在' }
            ctx.body = {
                state:'ok',
                data:docs
            }
            await ctx.model.Question.updateOne({ _id },{ $inc:{ view_count:1 } })
        } catch (e) {
            ctx.body = {
                state:'err'
            }
        }
    }

    async createReply () {
        const { ctx } = this
        const { content,content_html,question_id,image_field } = ctx.request.body

        if (await ctx.model.Reply.countDocuments({ question_id,user_id:ctx.user._id }) >= 1) {
            ctx.body = {
                state:'err',
                errMsg:'已经回答了!'
            }
            return
        }


        const docs = await ctx.model.Reply.create({ content,content_html,question_id,user_id:ctx.user._id,image_field })
        const question = await ctx.model.Question.findOneAndUpdate({ _id:question_id },{
            $inc:{ reply_count:1 },
            $push:{ reply_id:{ reply:docs._id,user:ctx.user._id } }
        },{ new:true })

        ctx.body = {
            state:'ok',
            data:docs,
            question
        }
        await Promise.all([
            ctx.model.User.updateOne({ _id:ctx.user._id },{ $inc:{ reply_count:1 } }),
            ctx.model.Dynamic.create({ user_id:ctx.user._id,type:'回答了问题',reply_id:docs._id })
        ])
        if (ctx.user._id.toString() === question.user_id.toString()) return
        await ctx.model.Notice.create({
            type:'消息',
            text:'回答了你的问题',
            user_id:question.user_id,
            res_user_id:ctx.user._id,
            res_reply_id:docs._id,
            question_id:question._id
        })
        ctx.service.notice.emit(question.user_id)
    }

    async getReply () {
        const { ctx } = this
        const { question_id,reply_id,page } = ctx.query

        let docs
        if (reply_id) {
            docs = await ctx.model.Reply.find({ _id:reply_id }).populate({
                path:'user_id',
                select:{ nickname:1,avatar:1,one_sentence_introduction:1,fans:1 }
            }).skip((page - 1) * 8).limit(8)
        } else {
            docs = await ctx.model.Reply.find({ question_id }).populate({
                path:'user_id',
                select:{ nickname:1,avatar:1,one_sentence_introduction:1,fans:1 }
            }).skip((page - 1) * 8).limit(8)

        }

        ctx.body = {
            state:'ok',
            data:docs
        }
    }

    async getReplyNin () {
        const { ctx } = this
        const { question_id,reply_id,page } = ctx.query


        const docs = await ctx.model.Reply.find({ question_id,_id:{ $nin:[reply_id] } })
            .populate({
                path:'user_id',
                select:{ nickname:1,avatar:1,one_sentence_introduction:1,fans:1 }
            })
            .sort({ _id:-1 })
            .skip((page - 1) * 8)
            .limit(8)

        ctx.body = {
            state:'ok',
            data:docs
        }
    }

    //赞同回答 下次干掉if
    async voters () {
        const { ctx } = this
        const { like,reply_id } = ctx.request.body


        let docs

        // 已经点踩的情况下点赞
        if (like.type === 'up' && like.flag === '1') {
            docs = await ctx.model.Reply.findOneAndUpdate({ _id:reply_id },{
                $inc:{ like_count:1 },
                $push:{ like_id:ctx.user._id },
                $pull:{ no_like_id:ctx.user._id }
            },{ new:true,select:{ like_count:1,user_id:1,question_id:1 } })
        }
        // 已经点赞的情况下点踩
        if (like.type === 'down' && like.flag === '1') {
            docs = await ctx.model.Reply.findOneAndUpdate({ _id:reply_id },{
                $inc:{ like_count:-1 },
                $push:{ no_like_id:ctx.user._id },
                $pull:{ like_id:ctx.user._id }
            },{ new:true,select:{ like_count:1,user_id:1,question_id:1 } })
        }
        // 点赞
        if (like.type === 'up' && like.flag === '2') {
            docs = await ctx.model.Reply.findOneAndUpdate({ _id:reply_id },{
                $inc:{ like_count:1 },
                $push:{ like_id:ctx.user._id }
            },{ new:true,select:{ like_count:1,user_id:1,question_id:1 } })
        }
        // 点踩
        if (like.type === 'down' && like.flag === '2') {
            docs = await ctx.model.Reply.findOneAndUpdate({ _id:reply_id },{
                $inc:{ like_count:-1 },
                $push:{ no_like_id:ctx.user._id }
            },{ new:true,select:{ like_count:1,user_id:1,question_id:1 } })
        }
        // 取消赞
        if (like.type === 'up' && like.flag === '3') {
            docs = await ctx.model.Reply.findOneAndUpdate({ _id:reply_id },{
                $inc:{ like_count:-1 },
                $pull:{ like_id:ctx.user._id }
            },{ new:true,select:{ like_count:1,user_id:1,question_id:1 } })
        }
        // 取消踩
        if (like.type === 'down' && like.flag === '3') {
            docs = await ctx.model.Reply.findOneAndUpdate({ _id:reply_id },{
                $inc:{ like_count:1 },
                $pull:{ no_like_id:ctx.user._id }
            },{ new:true,select:{ like_count:1,user_id:1,question_id:1 } })
        }

        ctx.body = {
            state:'ok',
            data:docs
        }

        if (like.type === 'up') {
            await ctx.model.User.updateOne({ _id:docs.user_id },{ $inc:{ like_count:1 } })

        }
        if (like.type === 'down') {
            await ctx.model.User.updateOne({ _id:docs.user_id },{ $inc:{ like_count:-1 } })
        }


        if ((like.type === 'up' && like.flag === '2') || (like.type === 'up' && like.flag === '1')) {
            try {
                await ctx.model.Dynamic.create({ user_id:ctx.user._id,type:'赞同了回答',reply_id })
                if (ctx.user._id.toString() === docs.user_id.toString()) return

                const isCheck = await ctx.model.Notice.countDocuments({
                    type:'赞同',
                    text:'赞同了你的回答',
                    user_id:docs.user_id,
                    question_id:docs.question_id,
                    res_user_id:ctx.user._id,
                    reply_id:docs._id
                })
                if (isCheck) return
                await ctx.model.Notice.create({
                    type:'赞同',
                    text:'赞同了你的回答',
                    user_id:docs.user_id,
                    question_id:docs.question_id,
                    res_user_id:ctx.user._id,
                    reply_id:docs._id
                })
                ctx.service.notice.emit(docs.user_id)
            } catch (e) {

            }
        }


        if (like.type === 'up' && like.flag === '3') {
            await ctx.model.Dynamic.deleteOne({ user_id:ctx.user._id,type:'赞同了回答',reply_id })
        }
        if (like.type === 'down' && like.flag === '1') {
            await ctx.model.Dynamic.deleteOne({ user_id:ctx.user._id,type:'赞同了回答',reply_id })
        }
        if (like.type === 'down' && like.flag === '2') {
            await ctx.model.Dynamic.deleteOne({ user_id:ctx.user._id,type:'赞同了回答',reply_id })
        }
    }

    async focus () {
        const { ctx } = this
        const { _id,type } = ctx.query
        let docs

        if (type === 'up') {
            [docs] = await Promise.all([
                ctx.model.Question.findOneAndUpdate({ _id },{
                    $inc:{ focus_problem_count:1 },
                    $push:{ focus_problem:ctx.user._id }
                },{ new:true,select:{ focus_problem:1 } }),
                ctx.model.Dynamic.create({ user_id:ctx.user._id,type:'关注了问题',question_id:_id })
            ])


        }

        if (type === 'down') {
            [docs] = await Promise.all([
                ctx.model.Question.findOneAndUpdate({ _id },{
                    $inc:{ focus_problem_count:-1 },
                    $pull:{ focus_problem:ctx.user._id }
                },{ new:true,select:{ focus_problem:1 } }),
                ctx.model.Dynamic.deleteOne({ user_id:ctx.user._id,type:'关注了问题',question_id:_id })
            ])
        }


        console.log(docs)

        ctx.body = {
            state:'ok',
            data:docs
        }

    }

    async searchList () {
        const { ctx } = this
        const { search,page } = ctx.query
        const reg = eval('/' + search + '/')

        const docs = await ctx.model.Question
            .find({
                $or:[{ title:reg }]
            })
            .populate({
                path:'reply_id.reply',
                select:{ content:1,like_count:1,image_field:1 }
            })
            .populate({
                path:'reply_id.user',
                select:{ nickname:1 }
            })
            .sort({ _id:-1 })
            .skip((page - 1) * 8)
            .limit(8)
        ctx.body = {
            state:'ok',
            data:docs
        }
    }

    async PeopleReply () {
        const { ctx } = this
        const { _id,page } = ctx.query

        const docs = await ctx.model.Reply
            .find({ user_id:_id })
            .populate({ path:'question_id',select:{ title:1 } })
            .populate({
                path:'user_id',
                select:{ avatar:1,nickname:1 }
            })
            .sort({ _id:-1 })
            .skip((page - 1) * 8)
            .limit(8)
        ctx.body = {
            state:'ok',
            data:docs
        }
    }

    async PeopleQuestion () {
        const { ctx } = this
        const { _id,page } = ctx.query

        const docs = await ctx.model.Question
            .find({ user_id:_id })
            .sort({ _id:-1 })
            .skip((page - 1) * 8)
            .limit(8)
        ctx.body = {
            state:'ok',
            data:docs
        }
    }

    async PeopleAttentionReply () {
        const { ctx } = this
        const { page,attentionList } = ctx.request.body
        const docs = await ctx.model.Reply.find({ user_id:{ $in:attentionList } })
            .populate({ path:'question_id',select:{ title:1,reply_count:1 } })
            .populate({ path:'user_id',select:{ avatar:1,nickname:1 } })
            .sort({ _id:-1 })
            .skip((page - 1) * 8)
            .limit(8)

        ctx.body = {
            state:'ok',
            data:docs
        }
    }

    async HotList () {
        const { ctx } = this
        const { page,type } = ctx.query


        let docs

        if (type === '全站') {
            docs = await ctx.model.Question.find({ view_count:{ $ne:0 } })
                .select({ content_html:0,comment:0 })
                .sort({ view_count:-1 })
                .skip((page - 1) * 8)
                .limit(8)
        } else {
            docs = await ctx.model.Question.find({ topic:{ $in:[type] },view_count:{ $ne:0 } })
                .select({ content_html:0,comment:0 })
                .sort({ view_count:-1 })
                .skip((page - 1) * 8)
                .limit(8)
        }


        ctx.body = {
            state:'ok',
            data:docs
        }
    }
}

module.exports = QuestionController
